package com.ellfors.common.widget

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.res.Resources
import android.graphics.PixelFormat
import android.util.DisplayMetrics
import android.util.TypedValue
import android.view.Gravity
import android.view.MotionEvent
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.ImageView
import android.widget.RelativeLayout
import com.ellfors.common.R
import com.ellfors.common.developer.DeveloperController
import kotlin.math.abs

/**
 * 开发者入口悬浮View
 */
@SuppressLint("ViewConstructor")
class DeveloperFloatView(activity: Activity) : RelativeLayout(activity) {

    private val dpi: Int
    private val screenHeight: Int
    private val screenWidth: Int
    private val wmParams: WindowManager.LayoutParams
    private val wm: WindowManager
    private var x = 0f
    private var y = 0f
    private var mTouchStartX = 0f
    private var mTouchStartY = 0f
    private var isScroll = false

    private var mClickListener: (() -> Unit)? = {
        DeveloperController.showDeveloper()
    }

    companion object {
        // 悬浮栏位置
        private const val LEFT = 0
        private const val RIGHT = 1
        private const val TOP = 3
        private const val BUTTOM = 4

        //宽高
        private const val IMAGE_WIDTH = 50
        private const val IMAGE_HEIGHT = 50
        private const val LAYOUT_MARGIN_BOTTOM = 150

        private val DEVELOPER_ICON = R.drawable.ic_developer
    }

    init {
        addImageView(activity)
        wm = activity.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val dm = DisplayMetrics()
        activity.windowManager.defaultDisplay.getMetrics(dm)
        //通过像素密度来设置按钮的大小
        dpi = dpi(dm.densityDpi)
        //屏宽
        screenWidth = wm.defaultDisplay.width
        //屏高
        screenHeight = wm.defaultDisplay.height
        //布局设置
        wmParams = WindowManager.LayoutParams().apply {
            // 设置window type
            type = WindowManager.LayoutParams.TYPE_APPLICATION
            // 设置图片格式，效果为背景透明
            format = PixelFormat.RGBA_8888
            gravity = Gravity.START or Gravity.TOP
            // 设置Window flag
            flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
            width = ViewGroup.LayoutParams.WRAP_CONTENT
            height = ViewGroup.LayoutParams.WRAP_CONTENT
            y = screenHeight - LAYOUT_MARGIN_BOTTOM.dp2px()
        }
        wm.addView(this, wmParams)
        hide()
    }

    private fun addImageView(activity: Activity) {
        ImageView(activity).apply {
            layoutParams = LayoutParams(
                IMAGE_WIDTH.dp2px(),
                IMAGE_HEIGHT.dp2px()
            )
            scaleType = ImageView.ScaleType.FIT_XY
            setImageResource(DEVELOPER_ICON)
        }.also {
            addView(it)
        }
    }

    /**
     * 根据密度选择控件大小
     *
     */
    private fun dpi(densityDpi: Int): Int {
        return when {
            densityDpi <= 120 -> 36
            densityDpi <= 160 -> 48
            densityDpi <= 240 -> 72
            densityDpi <= 320 -> 96
            else -> 108
        }
    }

    fun setOnClickListener(listener: () -> Unit) {
        mClickListener = listener
    }

    fun show() {
        if (isShown) {
            return
        }
        visibility = VISIBLE
    }

    fun hide() {
        visibility = GONE
    }

    fun destroy() {
        hide()
        wm.removeViewImmediate(this)
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        // 获取相对屏幕的坐标， 以屏幕左上角为原点
        x = event.rawX
        y = event.rawY
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                // 获取相对View的坐标，即以此View左上角为原点
                mTouchStartX = event.x
                mTouchStartY = event.y
            }
            MotionEvent.ACTION_MOVE -> {
                when {
                    isScroll -> {
                        updateViewPosition()
                        isScroll = true
                    }
                    abs(mTouchStartX - event.x) > dpi / 3 || abs(mTouchStartY - event.y) > dpi / 3 -> {
                        // 当前不处于连续滑动状态 则滑动小于图标1/3则不滑动
                        updateViewPosition()
                        isScroll = true
                    }
                }
            }
            MotionEvent.ACTION_UP -> {
                // 拖动
                if (isScroll) {
                    autoView()
                } else {
                    mClickListener?.invoke()
                }
                isScroll = false
                mTouchStartY = 0f
                mTouchStartX = mTouchStartY
            }
        }
        return false
    }

    /**
     * 自动移动位置
     */
    private fun autoView() {
        // 得到view在屏幕中的位置
        val location = IntArray(2)
        getLocationOnScreen(location)
        //左侧
        if (location[0] < screenWidth / 2 - width / 2) {
            updateViewPosition(LEFT)
        } else {
            updateViewPosition(RIGHT)
        }
    }

    /**
     * 手指释放更新悬浮窗位置
     */
    private fun updateViewPosition(l: Int) {
        when (l) {
            LEFT -> wmParams.x = 0
            RIGHT -> wmParams.x = screenWidth - dpi
            TOP -> wmParams.y = 0
            BUTTOM -> wmParams.y = screenHeight - dpi
        }
        wm.updateViewLayout(this, wmParams)
    }

    // 更新浮动窗口位置参数
    private fun updateViewPosition() {
        wmParams.x = (x - mTouchStartX).toInt()
        //是否存在状态栏（提升滑动效果）
        // 不设置为全屏（状态栏存在） 标题栏是屏幕的1/25
        wmParams.y = (y - mTouchStartY - screenHeight / 25).toInt()
        wm.updateViewLayout(this, wmParams)
    }

    fun Int.dp2px(): Int {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            this.toFloat(),
            Resources.getSystem().displayMetrics
        ).toInt()
    }
}